package cn.openea.perpartner.payment.config;

import org.jetbrains.annotations.NotNull;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.CustomExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author Administrator
 */
@Configuration
public class RabbitConfig implements EnvironmentAware {
    private Environment env;


    @Override
    public void setEnvironment(@NotNull Environment environment) {
        this.env = environment;
    }

    /**
     * 延时交换机
     *
     * @return 延时交换机
     */
    @Bean
    public CustomExchange delayExchange() {
        Map<String, Object> arguments = new HashMap<>(1);
        arguments.put("x-delayed-type", "direct");
        // 属性参数:交换机名称 交换机类型 是否持久化 是否自动删除 配置参数
        return new CustomExchange(env.getProperty("rabbit.delay.exchange"), "x-delayed-message", true, false, arguments);
    }



    /**
     * 延时发送队列,业务队列
     * @return 延时发送队列。
     */
    @Bean
    public Queue businessQueue() {
        return new Queue(Objects.requireNonNull(env.getProperty("rabbit.business.queue")), true, false, false);
    }

    /**
     * 延时绑定区,业务绑定区
     * @return 延时绑定区
     */
    @Bean
    public Binding businessBind() {
        return BindingBuilder.bind(this.businessQueue())
                .to(this.delayExchange())
                .with(env.getProperty("rabbit.business.routing_key"))
                .noargs();
    }



    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean("batchQueueRabbitListenerContainerFactory")
    public SimpleRabbitListenerContainerFactory batchQueueRabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        //设置批量
        factory.setBatchListener(true);
        //设置BatchMessageListener生效
        factory.setConsumerBatchEnabled(true);
        //设置监听器一次批量处理的消息数量
        factory.setBatchSize(1000);
        //设置线程数
        factory.setConcurrentConsumers(5);
        //最大线程数
        factory.setMaxConcurrentConsumers(10);
        return factory;
    }

}
